package com.fly.demo.web;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * RestPicController
 * 
 * @author 00fly
 * @version [版本号, 2021年9月28日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Api(tags = "图片接口")
@RestController
@ConditionalOnWebApplication
public class RestPicController
{
    @Autowired
    HttpSession session;
    
    @Autowired
    Producer producer;
    
    @ApiOperation("图片验证码")
    @GetMapping(value = "/captcha.jpg", produces = MediaType.IMAGE_JPEG_VALUE)
    public void captcha(HttpServletResponse response)
        throws IOException
    {
        // 生成文字验证码
        String text = producer.createText();
        // 生成图片验证码
        BufferedImage image = producer.createImage(text);
        // 保存到session
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        try (ServletOutputStream out = response.getOutputStream())
        {
            ImageIO.write(image, "jpg", out);
        }
    }
}
